package app

import (
	"administrator/app/mapper"
	"database/sql"
	"embed"
	"gitee.com/aurora-engine/aurora"
	"gitee.com/aurora-engine/gobatis"
	_ "github.com/go-sql-driver/mysql"
	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
)

/*
	服务器依赖初始化
*/

// GoBatis 初始化加载 mapper
func GoBatis(mapperFiles embed.FS) aurora.Option {
	return func(engine *aurora.Engine) {
		var driver string
		var b = false
		if mapperFiles == (embed.FS{}) {
			panic("mapperFiles embed.FS is {}")
		}
		config := engine.GetConfig()
		mapString := config.GetStringMapString("aurora.go-batis")
		if driver, b = mapString["driver"]; !b && driver == "" {
			panic("aurora. go-batis.driver error")
		}
		// 读取数据库配置
		getString := config.GetString("aurora.database." + driver + ".url")

		open, err := sql.Open("mysql", getString)
		if err != nil {
			panic("open db error:" + err.Error())
		}
		err = open.Ping()
		if err != nil {
			panic("Ping error:" + err.Error())
		}

		batis := gobatis.New(open)
		batis.Logs(engine.Log)
		batis.Load(mapperFiles)
		batis.Source("static/db/mappers")
		mappers := []any{
			new(mapper.UserMapper),
			new(mapper.MenuManageMapper),
			new(mapper.OrgManageMapper),
			new(mapper.RoleManageMapper),
			new(mapper.RbacManageMapper),
			new(mapper.AccountManageMapper),
			new(mapper.FuncManageMapper),
			new(mapper.ToolManageMapper),
		}
		batis.ScanMappers(mappers...)
		engine.Use(mappers...)
		engine.Use(open)
	}
}

// RabbitMQ 初始化消息队列
func RabbitMQ() aurora.Option {
	return func(engine *aurora.Engine) {
		config := engine.GetConfig()
		// RabbitMq
		mqurl := config.GetString("aurora.rabbitmq.addr")
		conn, err := amqp.Dial(mqurl)
		if err != nil {
			panic("Failed to connect to RabbitMQ")
		}
		channel, err := conn.Channel()
		if err != nil {
			panic(err)
		}
		// 创建用户消息队列
		//err = channel.ExchangeDeclare("userMsg", amqp.ExchangeTopic, true, false, false, false, nil)
		engine.Use(conn, channel)
	}
}

// Oos 对象存储
func Oos() aurora.Option {
	return func(engine *aurora.Engine) {
		config := engine.GetConfig()
		// 腾讯云对象存储配置
		ossConfig := config.GetStringMapString("aurora.oss")
		u, _ := url.Parse(ossConfig["bucketurl"])
		su, _ := url.Parse(ossConfig["serviceurl"])
		b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
		client := cos.NewClient(b, &http.Client{
			Transport: &cos.AuthorizationTransport{
				SecretID:  ossConfig["secretid"],
				SecretKey: ossConfig["secretkey"],
			},
		})
		engine.Use(client)
	}
}
